﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using System.Reflection;
using Module = Autofac.Module;

namespace Future.Web.Utility
{
    /// <summary>
    /// autofac注册
    /// </summary>
    public class CustomAutofacModule : Module
    {
        /// <summary>
        /// 获取要注册的dll
        /// </summary>
        /// <param name="ass"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private static Assembly GetDll(string ass)
        {
            var basePath = AppContext.BaseDirectory;
            var servicesDllFile = Path.Combine(basePath, ass);
            if (!(File.Exists(servicesDllFile)))
            {
                var msg = "dll丢失，请编译后重新生成。";
                throw new Exception(msg);
            }
            return Assembly.LoadFrom(servicesDllFile);
        }

        /// <summary>
        /// 重写load方法注册类到容器中
        /// </summary>
        /// <param name="containerBuilder"></param>
        protected override void Load(ContainerBuilder containerBuilder)
        {
            //注册AOP
            containerBuilder.RegisterType(typeof(CustomAutofacAop));

            //注册业务逻辑层
            Assembly assemblyBLL = GetDll("Future.BLL.dll");
            containerBuilder.RegisterAssemblyTypes(assemblyBLL)
                     .AsImplementedInterfaces()
                     .InstancePerLifetimeScope()
                     //AOP切入
                     .EnableInterfaceInterceptors()
                     .InterceptedBy(typeof(CustomAutofacAop));

            //注册数据访问层
            Assembly assemblyDAL = GetDll("Future.DAL.dll");
            containerBuilder.RegisterAssemblyTypes(assemblyDAL)
                     .AsImplementedInterfaces()
                     .PropertiesAutowired()
                     .InstancePerLifetimeScope();

            //注册服务
            Assembly assemblyService = GetDll("Future.Service.dll");
            containerBuilder.RegisterAssemblyTypes(assemblyService)
                     .AsImplementedInterfaces()
                     .InstancePerLifetimeScope();
        }
    }
}
